package com.bwei.topnews.utils;

import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.view.View;

import com.bwei.topnews.app.MyApplication;

/**
 * Created by qwe on 2016/10/31.
 */
public class CommonUtils {

    public static final String TAG = "NewsTop";
    private static SharedPreferences sharedPreferences;

    public static View inflate(int layouId) {
        View view = View.inflate(MyApplication.getContext(), layouId, null);
        return view;
    }

    public static int dip2px(int dip) {
        // 获取像素密度
        float density = MyApplication.getContext().getResources().getDisplayMetrics().density;
        int px = (int) (density * dip + 0.5f);
        return px;
    }

    public static int px2dip(int px) {
        // 获取像素密度
        float density = MyApplication.getContext().getResources().getDisplayMetrics().density;
        int dip = (int) (px / density + 0.5f);
        return dip;
    }

    public static String getString(int strId) {
        return MyApplication.getContext().getResources().getString(strId);
    }

    public static Drawable getDrawable(int did) {
        return MyApplication.getContext().getResources().getDrawable(did);
    }

    public static void saveSp(String flag, String str) {
        if (sharedPreferences == null) {
            sharedPreferences = MyApplication.getContext().getSharedPreferences(TAG, MyApplication.getContext().MODE_PRIVATE);
        }
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putString(flag, str);
        edit.commit();
    }

    public static String getSp(String flag) {
        if (sharedPreferences == null) {
            sharedPreferences = MyApplication.getContext().getSharedPreferences(TAG, MyApplication.getContext().MODE_PRIVATE);
        }
        String string = sharedPreferences.getString(flag, "");
        return string;
    }
    public static void clearSp(String flag){
        if (sharedPreferences == null) {
            sharedPreferences = MyApplication.getContext().getSharedPreferences(TAG, MyApplication.getContext().MODE_PRIVATE);
        }
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.remove(flag);
        edit.commit();
    }

    public static void OnRunUIThread(Runnable runnable) {
        // 判断当前线程ID是否与主线程ID相同
        if (android.os.Process.myTid() == MyApplication.getMyTid()) {
            runnable.run();
        } else {
            // 否则子线程
            MyApplication.getHandler().post(runnable);
        }
    }

    public static void executeRunnable(Runnable runnable) {
        MyApplication.getThreadPool().execute(runnable);
    }
}
